package com.yygo.service.impl;

import com.yygo.Constants;
import com.yygo.dao.BondDao;
import com.yygo.model.BondCompany;
import com.yygo.model.Dealer;
import com.yygo.model.User;
import com.yygo.model.vo.BondCompanyVO;
import com.yygo.service.BondManager;
import com.yygo.service.RoleManager;
import com.yygo.service.UserExistsException;
import com.yygo.service.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by tiansha on 2015/8/8.
 */
@Service("bondManager")
public class BondManagerImpl extends GenericManagerImpl<BondCompany, Long> implements BondManager {
    private BondDao bondDao;

    @Autowired
    private UserManager userManager;
    @Autowired
    private RoleManager roleManager;

    @Autowired
    public BondManagerImpl(BondDao bondDao) {
        super(bondDao);
        this.bondDao = bondDao;
    }

    @Override
    public BondCompany loadBond(Long id) {
        return bondDao.loadBond(id);
    }

  @Override
  public BondCompanyVO loadChildTree(Long id){
    return bondDao.loadChildTree(id);
  }
  @Override
  public List<BondCompanyVO> loadAllChildTree(){
    List<BondCompany> list = bondDao.getAll();
    List<BondCompanyVO> bondCompanyVOs = new ArrayList<>();
    for (BondCompany bondCompany: list){
      if(bondCompany.getParent()==null){
        bondCompanyVOs.add(bondDao.loadChildTree(bondCompany.getId())) ;
      }
    }
    return bondCompanyVOs;
  }

    @Override
    public Set<Dealer> getDealers(Long bondId) {
        return bondDao.getDealers(bondId);
    }

    @Override
    public BondCompany load(Long bondId) {
        return bondDao.load(bondId);
    }

    @Override
    public void saveBond(BondCompany bondCompany) throws UserExistsException {
        User user = bondCompany.getBondUser();
        user.setEnabled(true);
        user.getRoles().clear();
        user.addRole(roleManager.getRole(Constants.Bond_USER_ROLE));
        if (bondCompany.isMasterProvider() || bondCompany.isSlaveProvider()) {
            user.addRole(roleManager.getRole(Constants.Insurance_ROLE));
        }
        User adminUser = userManager.saveUser(user);
        bondCompany.setBondUser(adminUser);
        save(bondCompany);
    }
}
